package com.yxkj.railservicer.activity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.yxkj.railservicer.R;
import com.yxkj.railservicer.application.MyApplication;
import com.yxkj.railservicer.pager.BasePager;
import com.yxkj.railservicer.pager.QiangDan;
import com.yxkj.railservicer.pager.QuHuo;
import com.yxkj.railservicer.pager.SongDa;
import com.yxkj.railservicer.util.ChannelStatusConsts;
import com.yxkj.railservicer.util.HeartBreakUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.ScreenUtils;
import com.yxkj.railservicer.util.SysApplicationUtil;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "TAG";
    public static boolean isStart = true;
    private ImageView iv_main_back;
    private ImageView iv_main_setting;
    private RadioGroup rg_main;
    private RadioButton rb_main_qiangdan;
    private RadioButton rb_main_quhuo;
    private RadioButton rb_main_songda;
    private ViewPager vp_main;
    public List<BasePager> basePagers;

    private static boolean isExit = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SysApplicationUtil.getInstance().addActivity(this);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#2387f5"));


        //channel info上线
        try {
            String rid = JPushInterface.getRegistrationID(getApplicationContext());
            SPUtil.setString(MyApplication.getContext(), "channelId", rid);

            HeartBreakUtil.sendHeartBreakPacket(null, MyApplication.getContext(), ChannelStatusConsts.CHANNEL_STATUS_WORK);
            new HeartBreakUtil().startRepeatTask("YW_HEART_BREAK_EVENT");
        } catch (Exception e) {
            Log.e("EE", "发送心跳包出错");
            e.printStackTrace();
        }

        try {
            initData();
            initEvent();
        } catch (Exception e) {
            Log.e("EE", "初始化数据失败");
            e.printStackTrace();
        }

        try {
            //极光服务被停止，则重新启动极光推送
            if (JPushInterface.isPushStopped(MyApplication.getContext())) {
                Log.d("EE", "推送服务被停止，现在resume");
                JPushInterface.resumePush(MyApplication.getContext());
            }
        } catch (Exception e) {
            Log.e("EE", "极光推送resume失败");
        }


    }


    private void initData() {
        iv_main_back = (ImageView) findViewById(R.id.iv_main_back);
        iv_main_setting = (ImageView) findViewById(R.id.iv_main_setting);
        rg_main = (RadioGroup) findViewById(R.id.rg_main);
        rb_main_qiangdan = (RadioButton) findViewById(R.id.rb_main_qiangdan);
        rb_main_quhuo = (RadioButton) findViewById(R.id.rb_main_quhuo);
        rb_main_songda = (RadioButton) findViewById(R.id.rb_main_songdan);
        vp_main = (ViewPager) findViewById(R.id.vp_main);
        basePagers = new ArrayList<>();

    }


    private void initEvent() {
        iv_main_back.setVisibility(View.INVISIBLE);
        iv_main_setting.setOnClickListener(this);

        QiangDan qiangDan = new QiangDan(this);
        QuHuo quHuo = new QuHuo(this);
        SongDa songDa = new SongDa(this);


        basePagers.add(qiangDan);
        basePagers.add(quHuo);
        basePagers.add(songDa);
        //给viewPager添加适配器
        vp_main.setAdapter(new MyPagerAdapter());
        //按钮变化监听
        rg_main.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        //默认第一页
        vp_main.setCurrentItem(0);
        //默认第一个按钮
        rg_main.check(R.id.rb_main_qiangdan);
        //页面变化监听
        vp_main.setOnPageChangeListener(new MyOnPageChangeListener());
        //加载第一页数据
        qiangDan.initData();
        quHuo.initData();
        songDa.initData();

//        basePagers.get(1).initData();
//        basePagers.get(2).initData();
//        ((QuHuo)basePagers.get(1)).getInfo1();
//        ((SongDa)basePagers.get(2)).getInfo1();
    }

    public void getCount(BasePager pager, String count) {
        if (count == null) {
            count = "0";
        }

        if (pager instanceof QiangDan) {
            rb_main_qiangdan.setText("待抢单[" + count + "]");
        } else if (pager instanceof QuHuo) {
            rb_main_quhuo.setText("待取货[" + count + "]");
        } else {
            rb_main_songda.setText("待送达[" + count + "]");
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.iv_main_setting:
                intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * viewPager适配器
     */
    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return basePagers.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            BasePager basePager = basePagers.get(position);
            View rootView = basePager.rootView;
            container.addView(rootView);

            return rootView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 按钮变化监听
     */
    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_main_qiangdan:
                    vp_main.setCurrentItem(0);
                    rb_main_qiangdan.setTextColor(Color.parseColor("#248cf5"));
                    rb_main_quhuo.setTextColor(Color.parseColor("#aaaaaa"));
                    rb_main_songda.setTextColor(Color.parseColor("#aaaaaa"));
                    break;
                case R.id.rb_main_quhuo:
                    vp_main.setCurrentItem(1);
                    rb_main_qiangdan.setTextColor(Color.parseColor("#aaaaaa"));
                    rb_main_quhuo.setTextColor(Color.parseColor("#248cf5"));
                    rb_main_songda.setTextColor(Color.parseColor("#aaaaaa"));
                    break;
                case R.id.rb_main_songdan:
                    vp_main.setCurrentItem(2);
                    rb_main_qiangdan.setTextColor(Color.parseColor("#aaaaaa"));
                    rb_main_quhuo.setTextColor(Color.parseColor("#aaaaaa"));
                    rb_main_songda.setTextColor(Color.parseColor("#248cf5"));
                    break;
            }
        }
    }

    /**
     * 页面变化监听
     */
    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            Log.e(TAG, "onPageSelected: " + position);
            //滑动某页加载对应页的数据
            basePagers.get(position).initData();
            //手动滑动时候找到对应的RadioButton
            ((RadioButton) rg_main.getChildAt(position)).setChecked(true);

        }

        @Override
        public void onPageScrollStateChanged(int state) {
//            Log.e(TAG, "onPageScrollStateChanged: " + state);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
//            System.exit(0);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        isStart = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStart = false;
    }

    @Override
    protected void onDestroy() {
        SysApplicationUtil.getInstance().deleteActivity(this);
        JPushInterface.stopPush(MyApplication.getContext());
        Log.e(TAG, "解绑成功");
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        vp_main.setCurrentItem(0);
        initOne();
    }

    public void initPager() {

//        ((QiangDan) basePagers.get(0)).initData();
        ((QiangDan) basePagers.get(0)).setPages(0);
        ((QuHuo) basePagers.get(1)).setPages(0);
        ((SongDa) basePagers.get(2)).setPages(0);
        ((QiangDan) basePagers.get(0)).getInfo1();
        ((QuHuo) basePagers.get(1)).getInfo1();
        ((SongDa) basePagers.get(2)).getInfo1();
//        basePagers.get(1).initData();
//        basePagers.get(2).initData();
    }

    public void initOne() {
//        basePagers.get(0).initData();
        ((QiangDan) basePagers.get(0)).setPages(0);
        ((QiangDan) basePagers.get(0)).getInfo1();
    }
}
